package com.store.handler;

import com.alibaba.fastjson.JSON;
import com.store.domain.R;
import com.store.utils.JwtUtil;
import com.store.utils.ThreadLocalUtil;
import com.store.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author yu
 * @date 2023/5/3
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        if (Objects.isNull(token)){
            R r = R.error("请登录后操作");
            r.setCode(3);
            WebUtils.renderString(response, JSON.toJSONString(r));
            return false;
        }


        //token合法
        Claims claims = null;
        try{
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e){
            //token 超时 token非法
            R r = R.error("请重新登录");
            r.setCode(3);
            WebUtils.renderString(response, JSON.toJSONString(r));
            return false;
        }
        Integer loginId = Integer.valueOf(claims.getSubject());
        ThreadLocalUtil.setLocal(loginId);
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        //离开的时候，将ThreadLocal释放
        ThreadLocalUtil.remove();
    }
}
